package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/6 20:01
 * https://leetcode-cn.com/problems/sqrtx/
 * 注意：范围
 */
public class Title69 {

    public int mySqrt(int x) {
        int left = 0, right = x / 2 + 1;
        while (left <= right) {
            int middle = (left + right) / 2;
            if ((long)middle * middle == x) {
                return middle;
            } else if ((long)middle * middle > x) {
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }
        return right;
    }

    public int mySqrt1(int x) {
        //right  = x/2+1 ; + 1 确保 x == 1 时，也成立的情况
        int left = 0, right = x / 2 + 1;
        while (left <= right) {
            int middle = left + (right - left) / 2;
            if ((long)middle * middle == x) {
                return middle;
            } else if ((long)middle * middle < x) {
                left = middle + 1;
            }else{
                right = middle - 1;
            }
        }
        return left - 1;
    }

    public static void main(String[] args) {

    }
}
